import { useState, useEffect } from "react";
import {
	Card,
	Form,
	Input,
	Button,
	Tabs,
	message,
	Select,
	InputNumber,
} from "antd";
import { useTranslation } from "react-i18next";
import {
	ConfigGroup,
	ConfigItem,
	configService,
} from "@/api/services/configService";
import { UploadBox } from "@/components/upload";

const SettingPage = () => {
	const { t } = useTranslation();
	const [loading, setLoading] = useState(false);
	const [groups, setGroups] = useState<ConfigGroup[]>([]);
	const [configs, setConfigs] = useState<Record<string, ConfigItem[]>>({});
	const [forms] = Form.useForm();

	// 获取配置组
	const fetchGroups = async () => {
		try {
			const groups = await configService.getGroups();
			setGroups(groups);
			// 获取第一个组的配置
			if (groups.length > 0) {
				fetchConfigByGroup(groups[0]);
			}
		} catch (error) {
			message.error("获取配置组失败");
		}
	};

	// 获取指定组的配置
	const fetchConfigByGroup = async (group: ConfigGroup) => {
		try {
			setLoading(true);
			const configs = await configService.getConfigByGroup(group);
			setConfigs((prev) => ({
				...prev,
				[group]: configs,
			}));

			// 设置表单初始值
			const initialValues: Record<string, any> = {};
			configs.forEach((item) => {
				let value = item.value;
				// 处理特殊类型的值
				if (item.type === "array" && value) {
					try {
						value = JSON.parse(value);
					} catch (e) {
						console.error("解析数组配置失败:", e);
					}
				}
				initialValues[item.name] = value;
			});
			forms.setFieldsValue(initialValues);
		} catch (error) {
			message.error("获取配置项失败");
		} finally {
			setLoading(false);
		}
	};

	// 处理标签页切换
	const handleTabChange = (group: ConfigGroup) => {
		if (!configs[group]) {
			fetchConfigByGroup(group);
		}
	};

	// 处理表单提交
	const handleSubmit = async (group: ConfigGroup, values: any) => {
		try {
			// 处理特殊类型的值
			const processedValues = { ...values };
			configs[group]?.forEach((item) => {
				if (item.type === "array" && processedValues[item.name]) {
					processedValues[item.name] = JSON.stringify(
						processedValues[item.name],
					);
				}
			});

			await configService.saveConfig(group, processedValues);
			message.success("保存成功");
		} catch (error) {
			message.error("保存失败");
		}
	};

	// 渲染配置项
	const renderFormItem = (config: ConfigItem) => {
		switch (config.type) {
			case "string":
				return <Input placeholder={config.tip} />;
			case "text":
				return <Input.TextArea rows={4} placeholder={config.tip} />;
			case "array":
				return (
					<Input.TextArea
						rows={4}
						placeholder={config.tip}
						onChange={(e) => {
							try {
								JSON.parse(e.target.value);
							} catch (error) {
								message.error("请输入有效的 JSON 格式");
							}
						}}
					/>
				);
			case "number":
				return (
					<InputNumber style={{ width: "100%" }} placeholder={config.tip} />
				);
			case "image":
				return (
					<UploadBox
						maxCount={1}
						value={config.value}
						onChange={(info) => {
							// 处理上传文件变化
						}}
					/>
				);
			default:
				return <Input placeholder={config.tip} />;
		}
	};

	useEffect(() => {
		fetchGroups();
	}, []);

	const items = groups.map((group) => ({
		key: group,
		label: group,
		children: (
			<Form
				form={forms}
				layout="vertical"
				onFinish={(values) => handleSubmit(group, values)}
				className="max-w-2xl"
			>
				{configs[group]?.map((config) => (
					<Form.Item
						key={config.id}
						label={config.title}
						name={config.name}
						rules={[
							{
								required: config.rule.includes("required"),
								message: `请输入${config.title}`,
							},
						]}
						tooltip={config.tip}
					>
						{renderFormItem(config)}
					</Form.Item>
				))}
				<Form.Item>
					<Button type="primary" htmlType="submit" loading={loading}>
						保存设置
					</Button>
				</Form.Item>
			</Form>
		),
	}));

	return (
		<Card>
			<Tabs
				defaultActiveKey={groups[0]}
				items={items}
				onChange={handleTabChange}
			/>
		</Card>
	);
};

export default SettingPage;
